package com.temp.controller.admin;

import com.temp.dto.PermDTO;
import com.temp.dto.SearchPermDTO;
import com.temp.entity.Permission;
import com.temp.result.Result;
import com.temp.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/admin/perm")
@Api(tags = "管理权限相关接口")
@Slf4j
@Validated
public class AdminPermController {

    @Autowired
    private PermissionService permissionService;

    @PostMapping("/query")
    @ApiOperation("查询权限信息")
    @RequiresPermissions("admin:perm:query")
    public Result getAllPerm(@RequestBody SearchPermDTO permDTO) {
        permDTO.formatParam();
        return Result.success(permissionService.findAllPermission(permDTO), "apiMsg.querySuccess");
    }

    @PostMapping("/updateOrSave")
    @ApiOperation("保存或者更新权限")
    @RequiresPermissions("admin:perm:updateOrSave")
    public Result updateOrSave(@Valid @RequestBody PermDTO permDTO) {
        Permission perm = new Permission();
        BeanUtils.copyProperties(permDTO, perm);
        boolean isSuccess = permissionService.saveOrUpdate(perm);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除权限")
    @RequiresPermissions("admin:perm:delete")
    public Result delPerm(@RequestParam Long id) {
        boolean isSuccess = permissionService.removeById(id);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }
}
